package com.nirvana.common.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.nirvana.common.constant.BaseMessage;
import com.nirvana.common.exception.BaseException;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 公共响应类
 *
 * @author zhangshuaiyin
 * @date 2021/5/31 21:58
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BaseResponse<T> implements Serializable {
    /**
     * 响应码
     */
    @ApiModelProperty(value = "响应码", required = true)
    private String code;

    /**
     * 响应描述
     */
    @ApiModelProperty(value = "响应描述", required = true)
    private String message;

    /**
     * 响应数据体
     */
    @ApiModelProperty(value = "响应数据")
    private T data;

    /**
     * 创建响应对象
     *
     * @param code    响应码
     * @param message 响应描述
     * @return 响应对象
     */
    public static <T> BaseResponse<T> of(String code, String message) {
        return of(code, message, null);
    }

    /**
     * 创建响应对象
     *
     * @param code    响应码
     * @param message 响应描述
     * @param data    响应数据
     * @return 响应对象
     */
    public static <T> BaseResponse<T> of(String code, String message, T data) {
        return new BaseResponse<>(code, message, data);
    }

    /**
     * 创建响应对象
     *
     * @param e 异常对象
     * @return 响应对象
     */
    public static <T> BaseResponse<T> of(BaseException e) {
        return of(e.getExceptionCode(), e.getExceptionMessage());
    }

    /**
     * 创建响应对象
     *
     * @param message 响应信息
     * @return 响应对象
     */
    public static <T> BaseResponse<T> of(BaseMessage message) {
        return of(message.getCode(), message.getMessage());
    }

    /**
     * 创建响应对象
     *
     * @param message 响应信息
     * @param data    响应对象
     * @return 响应对象
     */
    public static <T> BaseResponse<T> of(BaseMessage message, T data) {
        return of(message.getCode(), message.getMessage(), data);
    }

    public static <T> BaseResponse<T> ok(T data) {
        return BaseMessage.SUCCESS.response(data);
    }

    public static BaseResponse<BaseMessage> ok() {
        return BaseMessage.SUCCESS.response();
    }
}
